package com.hankol.feature_wine_meal

import android.annotation.SuppressLint
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.widget.NestedScrollView
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseActivity
import com.baselibrary.bean.CommentEnum
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.share.SharePopupWindow
import com.okhttp.comment.CommentBean
import com.hankol.feature_wine_meal.adapter.WineDetailsAdapter
import com.hankol.feature_wine_meal.api.OpenCommentCallBack
import com.hankol.feature_wine_meal.api.WineMealHelp
import com.hankol.feature_wine_meal.bean.FoodDetailsBean
import com.hankol.feature_wine_meal.databinding.ActivityWineMealDetaBinding
import com.hankol.feature_wine_meal.viewmodel.WineMealViewModel
import com.like.LikeButton
import com.like.OnLikeListener
import com.okhttp.comment.BusinessLayout
import com.okhttp.comment.CommentConstant
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener

/**
 * @description 下酒菜详情
 * @author 关忆北、
 * @time 2022/6/23 1:48 下午
 */
@Route(path = ActivityRouter.WINE_MEAL.WINE_MEAL_DETAILS)
class WineMealDetailsActivity : BaseActivity(), View.OnClickListener, OpenCommentCallBack, WineDetailsAdapter.OnShareClickListener {
    private var foodId: Long = 0
    private var pageNum: Int = 1
    private var mCommentTopId: Long = -1
    private var mDetailsBean: FoodDetailsBean? = null
    private var showShare: SharePopupWindow? = null
    private var mCommentBean: CommentBean.DataBean? = null
    private var isVisibility: Boolean = false
    private lateinit var mViewModel: WineMealViewModel
    private lateinit var dataBinding: ActivityWineMealDetaBinding
    private val mImageHeight = (ScreenUtils.getScreenWidth() / Constants.DYNAMIC_PICTURE_SCALE) / 2
    private val mAdapter: WineDetailsAdapter by lazy { WineDetailsAdapter(this@WineMealDetailsActivity, mViewModel, this) }
    private val mWineMealHelp = ActivityRouter.getARouterInterface<WineMealHelp>(ActivityRouter.WINE_MEAL.WINE_MEAL_HELP)
    private var drinkFoodPlateName = ""
    private var className = ""
    private var recommendName = ""

    companion object {
        public val DRINK_FOOD_PLATE_NAME: String = "DRINK_FOOD_PLATE_NAME"
        public val CLASS_NAME: String = "CLASS_NAME"
        public val RECOMMEND_NAME: String = "RECOMMEND_NAME"
    }

    override fun getLayoutId(): Int {
        initImmersion(true)
        return R.layout.activity_wine_meal_deta
    }

    override fun init() {
        SensorsDataManager.instance.onCreateTime()
        dataBinding = getDataBinding<ActivityWineMealDetaBinding>()
        mViewModel = getActivityViewModelProvider(this).get(WineMealViewModel::class.java)
        dataBinding.rvWineDetailsStep.adapter = mAdapter

        initView()
        initData()
        loadData()
        initListener()
        initObserve()

    }

    private fun initObserve() {
        mViewModel.commentListLiveData.observe(this, Observer {
            dataBinding.smartWineDetails.finishRefresh()
            dataBinding.smartWineDetails.finishLoadMore()
            dataBinding.bcvWineDetails.commentNetData(it, pageNum)
            if (it != null) {
                mCommentBean = it
                dataBinding.includeWineComment.tvCommentComCount.text = if (it.totalCount == 0) "抢首评" else NumberUtils.formatBigNum(it.totalCount.toString())
                if (it.totalCount <= 0) {
                    dataBinding.tvWineDetailsCommentNum.visibility = View.GONE
                } else {
                    dataBinding.tvWineDetailsCommentNum.visibility = View.VISIBLE
                    dataBinding.tvWineDetailsCommentNum.text = "共${it.totalCount}条评论"
                }
                if (mCommentTopId > 0) {
                    dataBinding.rvWineDetailsStep.post {
                        mCommentTopId = 0
                        dataBinding.nsv.smoothScrollTo(0, dataBinding.llWineDetailsComment.top - ScreenUtils.getStatusBarHeight(this))
                    }
                }
                if (it.normalList.isNotEmpty()) {
                    pageNum++
                }
            }
        })
        mViewModel.foodInfoLD.observe(this, Observer {
            hideLoadingDialog()
            dataBinding.smartWineDetails.finishRefresh()
            dataBinding.smartWineDetails.finishLoadMore()
            dataBinding.smartWineDetails.visibility = View.VISIBLE
            if (it != null) {
                mDetailsBean = it
                mAdapter.setData(it)
                dataBinding.tvWineDetailsTitle.text = it.name
                dataBinding.includeWineComment.ivCommentGiveState.isLiked = it.hasLiked == 1
                dataBinding.includeWineComment.llCommentGive.isSelected = it.hasLiked == 1
                dataBinding.includeWineComment.tvCommentGiveCount.text = if (it.supportNum <= 0) "点赞" else NumberUtils.formatBigNum(it.supportNum.toString())

                dataBinding.includeWineComment.ivCommentConState.isLiked = it.hasFavorite == 1
                dataBinding.includeWineComment.llCommentCollection.isSelected = it.hasFavorite == 1
                dataBinding.includeWineComment.tvCommentConCount.text = if (it.favoriteNum <= 0) "收藏" else NumberUtils.formatBigNum(it.favoriteNum.toString())
                //详情数据请求完成之后，在请求评论数据
                mViewModel.reqCommentList(pageNum, CommentEnum.COMMENT_XIAJIUCAI_NEW, foodId, mCommentTopId)
            }
        })

        mViewModel.supportLiveData.observe(this, Observer { it ->
            dataBinding.includeWineComment.ivCommentGiveState.isEnabled = true
            if (it) {
                mDetailsBean?.let {
                    mViewModel.upSupportSate(dataBinding, it)
                }
            }
        })

        mViewModel.collectionLiveData.observe(this, Observer { it ->
            if (it) {
                mDetailsBean?.let {
                    mViewModel.upCollectionSate(dataBinding, it)
                    dataBinding.includeWineComment.ivCommentConState.isEnabled = true
                    EventBusUtils.sendNotify1Value(MessageBus.msgId_change_dynamic_collect_status, it.id.toInt())
                }
            }
        })


    }

    fun initView() {
        dataBinding.llWineDetailsBack.setOnClickListener {
            finish()
        }

        dataBinding.llWineDetailsShare.setOnClickListener {
            mDetailsBean?.let {
                showShare = mViewModel.showShare(it, this, mWineMealHelp)
                mViewModel.reqFriendList()
            }
        }
        mViewModel.friendLiveData.observe(this, Observer {
            showShare?.setShareFriendAdapter(mViewModel.changeFriend(it))
        })
    }

    fun initData() {
        intent.extras?.let {
            if (ARouterUtils.parseParams(it, DRINK_FOOD_PLATE_NAME)[0].checkNotNull()) {
                drinkFoodPlateName = ARouterUtils.parseParams(it, DRINK_FOOD_PLATE_NAME)[0]
            }
            if (ARouterUtils.parseParams(it, CLASS_NAME)[0].checkNotNull()) {
                className = ARouterUtils.parseParams(it, CLASS_NAME)[0]
            }
            if (ARouterUtils.parseParams(it, RECOMMEND_NAME)[0].checkNotNull()) {
                recommendName = ARouterUtils.parseParams(it, RECOMMEND_NAME)[0]
            }

            if (ARouterUtils.parseParams(it, Constants.WINE_MEAL_DETAILS_ID)[0].checkNotNull()) {
                foodId = ARouterUtils.parseParams(it, Constants.WINE_MEAL_DETAILS_ID)[0].toLong()
            }

            if (ARouterUtils.parseParams(it, Constants.COMMENT_TOP_ID)[0].checkNotNull()) {
                mCommentTopId = ARouterUtils.parseParams(it, Constants.COMMENT_TOP_ID)[0].toLong()
            }
        }
        dataBinding.bcvWineDetails.setAdapter(this, null)
        dataBinding.bcvWineDetails.isEmptyView(false)
        dataBinding.circleWineDetailsCurrentHead.setData(SpUtils.getInstance().userICon, SpUtils.getInstance().loadUserBean.data.isFans == 1)


        dataBinding.tvWineDetailsTitle.alpha = 0f
        dataBinding.llTitle.setBackgroundColor(Color.argb(0, 255, 255, 255))
        dataBinding.ivWineDetailsBack.imageTintList = ColorStateList.valueOf(ContextCompat.getColor(applicationContext, R.color.white))
        dataBinding.ivWineDetailsShare.imageTintList = ColorStateList.valueOf(ContextCompat.getColor(applicationContext, R.color.white))
        val backShape: GradientDrawable = dataBinding.llWineDetailsBack.background as GradientDrawable
        val shareShape: GradientDrawable = dataBinding.llWineDetailsShare.background as GradientDrawable
        backShape.setColor(Color.argb(60, 0, 0, 0))
        shareShape.setColor(Color.argb(60, 0, 0, 0))
        showLoadingDialog()
    }

    fun loadData() {
        mViewModel.reqFoodInfo(foodId)
        isVisibility = mViewModel.getLocalVisibleRect(this@WineMealDetailsActivity, dataBinding.bcvWineDetails, 0)
    }

    fun initListener() {
        dataBinding.includeWineComment.llCommentSaySomething.setOnClickListener(this)
        dataBinding.includeWineComment.llCommentJumpCom.setOnClickListener(this)
        dataBinding.tvWineDetailsComment.setOnClickListener(this)
        dataBinding.includeWineComment.ivCommentGiveState.setOnLikeListener(object : OnLikeListener {
            override fun liked(likeButton: LikeButton?) {
                //点赞
                mDetailsBean?.let {
                    dataBinding.includeWineComment.ivCommentGiveState.isEnabled = false
                    mViewModel.reqSupport(true, 9, it.id.toInt())
                }
            }

            override fun unLiked(likeButton: LikeButton?) {
                //取消点赞
                mDetailsBean?.let {
                    dataBinding.includeWineComment.ivCommentGiveState.isEnabled = false
                    mViewModel.reqSupport(false, 9, it.id.toInt())
                }
            }

        })

        dataBinding.includeWineComment.ivCommentConState.setOnLikeListener(object : OnLikeListener {
            override fun liked(likeButton: LikeButton?) {
                //收藏
                mDetailsBean?.let {
                    dataBinding.includeWineComment.ivCommentConState.isEnabled = false
                    mViewModel.reqCollection(true, 8, it.id)
                }
            }

            override fun unLiked(likeButton: LikeButton?) {
                //取消收藏
                mDetailsBean?.let {
                    dataBinding.includeWineComment.ivCommentConState.isEnabled = false
                    mViewModel.reqCollection(false, 8, it.id)
                }
            }
        })

        dataBinding.smartWineDetails.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageNum = 1
                loadData()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                mViewModel.reqCommentList(pageNum, CommentEnum.COMMENT_XIAJIUCAI_NEW, foodId, mCommentTopId)
            }

        })
        dataBinding.nsv.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            isVisibility = mViewModel.getLocalVisibleRect(this@WineMealDetailsActivity, dataBinding.bcvWineDetails, scrollY)
            when {
                scrollY <= 0f -> {
                    dataBinding.tvWineDetailsTitle.alpha = 0f
                    dataBinding.llTitle.setBackgroundColor(Color.argb(0, 255, 255, 255))
                    dataBinding.ivWineDetailsBack.imageTintList = ColorStateList.valueOf(ContextCompat.getColor(applicationContext, R.color.white))
                    dataBinding.ivWineDetailsShare.imageTintList = ColorStateList.valueOf(ContextCompat.getColor(applicationContext, R.color.white))
                    val backShape: GradientDrawable = dataBinding.llWineDetailsBack.background as GradientDrawable
                    val shareShape: GradientDrawable = dataBinding.llWineDetailsShare.background as GradientDrawable
                    backShape.setColor(Color.argb(60, 0, 0, 0))
                    shareShape.setColor(Color.argb(60, 0, 0, 0))
                }
                scrollY <= mImageHeight -> {
                    val scale: Float = scrollY / mImageHeight
                    val alpha = 255 * scale
                    dataBinding.tvWineDetailsTitle.alpha = scale
                    dataBinding.llTitle.setBackgroundColor(Color.argb(alpha.toInt(), 255, 255, 255))
                    dataBinding.ivWineDetailsBack.imageTintList = ColorStateList.valueOf(ContextCompat.getColor(applicationContext, R.color.white))
                    dataBinding.ivWineDetailsShare.imageTintList = ColorStateList.valueOf(ContextCompat.getColor(applicationContext, R.color.white))

                    val backShape: GradientDrawable = dataBinding.llWineDetailsBack.background as GradientDrawable
                    val shareShape: GradientDrawable = dataBinding.llWineDetailsShare.background as GradientDrawable
                    backShape.setColor(Color.argb(30, 255, 255, 255))
                    shareShape.setColor(Color.argb(30, 255, 255, 255))
                }
                else -> {
                    dataBinding.tvWineDetailsTitle.alpha = 1f
                    dataBinding.tvWineDetailsTitle.visibility = View.VISIBLE
                    dataBinding.llTitle.setBackgroundColor(Color.argb(255, 255, 255, 255))
                    dataBinding.ivWineDetailsBack.imageTintList = ColorStateList.valueOf(ContextCompat.getColor(applicationContext, R.color.color_666666))
                    dataBinding.ivWineDetailsShare.imageTintList = ColorStateList.valueOf(ContextCompat.getColor(applicationContext, R.color.color_666666))

                    val backShape: GradientDrawable = dataBinding.llWineDetailsBack.background as GradientDrawable
                    val shareShape: GradientDrawable = dataBinding.llWineDetailsShare.background as GradientDrawable
                    backShape.setColor(Color.argb(255, 255, 255, 255))
                    shareShape.setColor(Color.argb(255, 255, 255, 255))
                }
            }
        })
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.ll_base_comment_empty, R.id.tv_wine_details_comment, R.id.ll_comment_saySomething -> {
                openCommentCall()
            }
            R.id.ll_comment_jumpCom -> {

                if (isVisibility) {
                    openCommentCall()
                } else {
                    dataBinding.rvWineDetailsStep.post {
                        isVisibility = true
                        dataBinding.nsv.smoothScrollTo(0, dataBinding.llWineDetailsComment.top - ScreenUtils.getStatusBarHeight(this))
                    }
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data != null) {
            dataBinding.bcvWineDetails.commentOnResult(requestCode, resultCode, data)
            dataBinding.bcvWineDetails.setSayContent(requestCode, resultCode, data, dataBinding.includeWineComment.tvCommentSaySomething, CommentConstant.COMMENT_DEF_CONTENT_VERSION_1)
            val commentNum: Int = dataBinding.bcvWineDetails.upCommentNum(requestCode, resultCode, data, mDetailsBean?.commentNum!!, dataBinding.includeWineComment.tvCommentComCount)
            if (commentNum != -1) {
                mDetailsBean?.commentNum = commentNum
                if (commentNum <= 0) {
                    dataBinding.tvWineDetailsCommentNum.visibility = View.GONE
                } else {
                    dataBinding.tvWineDetailsCommentNum.visibility = View.VISIBLE
                    dataBinding.tvWineDetailsCommentNum.text = "共${commentNum}条评论"
                }
                dataBinding.includeWineComment.tvCommentComCount.text = if (commentNum == 0) "抢首评" else NumberUtils.formatBigNum(commentNum.toString())

            }
        }
    }

    /**
     * 打开评论面板
     */
    override fun openCommentCall() {
        if (DoubleUtils.isFastDoubleClick()) return
        //进行评论
        BusinessLayout.openCommentActivity(this, CommentEnum.COMMENT_XIAJIUCAI_NEW.commentType, foodId.toInt(), dataBinding.includeWineComment.tvCommentSaySomething.text.toString().trim(), "", false, CommentConstant.COMMENT_REQUESTCODE)

    }

    override fun onDestroy() {
        mDetailsBean?.let {
            //离开界面是，发送点赞和收藏的最终状态
            EventBusUtils.sendNotify(if (it.hasLiked == 1) MessageBus.msgId_wine_meal_like_true else MessageBus.msgId_wine_meal_like_false)
            if (it.hasFavorite == 1) {
                if (mViewModel.upCollectionTime != 0L) {
                    //判断收藏时间是否发生变化
                    EventBusUtils.sendNotify1Value(MessageBus.msgId_wine_meal_collection_time, mViewModel.upCollectionTime)
                }
            } else {
                EventBusUtils.sendNotify(MessageBus.msgId_wine_meal_collection_false)
            }
            SensorsDataManager.instance.browseDrinkFood(drinkFoodPlateName, className, recommendName, it.name, SensorsDataManager.instance.getBrowseTime())
        }
        super.onDestroy()

    }

    override fun onWxShareClick() {
        mDetailsBean?.let {
            mWineMealHelp.wxShare(this@WineMealDetailsActivity, 0, mWineMealHelp.getShareUrl() + it.id, it.name, it.desc, it.cover, 1)
        }
    }

    override fun onWxCircleShareClick() {
        mDetailsBean?.let {
            mWineMealHelp.wxShare(this@WineMealDetailsActivity, 1, mWineMealHelp.getShareUrl() + it.id, it.name, it.desc, it.cover, 1)
        }
    }
}